<?php

/*
 *
 */

class Model_Mediate_CaseRepayLog extends Model_BaseModel
{
    use Lib_BaseTraits;
    /**
     * 缓存前缀
     *
     * @var unknown
     */
    private static $tag = 'Model_Mediate_CaseRepayLog';
    /**
     * Undocumented variable.
     *
     * @var string
     */
    private $table = 'case_repay_log';

    public function __construct()
    {
        // 选择连接的数据库
        parent::_init('mediation');
    }

    public function getDataBySearch($fields = array(), $search = array(), $cache = false)
    {
        $fields = empty($fields) ? '*' : implode(',', $fields);
        $search_str = 'WHERE 1 ';
        if (isset($search['where']) && !empty($search['where'])) {
            $search_str .= ' AND '.implode(' AND ', $search['where']);
        }
        $search_str .= '';
        if (isset($search['order']) && $search['order']) {
            $search_str .= ' ORDER BY '.$search['order'];
        }
        if (isset($search['limit']) && $search['limit']) {
            $search['start'] = isset($search['start']) ? $search['start'] : 0;
            $search_str .= ' LIMIT '.$search['start'].','.$search['limit'];
        }
        $sql = "SELECT {$fields} FROM case_repay_log left join cases ON case_repay_log.case_id = cases.id {$search_str}";
        //echo $sql;die;
        $cache ? $this->dao->conn()->setTag(self::$tag) : $this->dao->conn(false)->noCache();
        $res = $this->dao->preparedSql($sql, array())->fetchAll();

        return $res;
    }

    /**
     * @desc 分页查询 获取上一页 下一页 id
     *
     * @param int $type 1上一页  2 下一页
     *
     * @return mixed
     */
    public function getPageId($type, $id, $adm_id)
    {
        $data = [];
        $sql = "SELECT l.*,c.mediator_id FROM `case_repay_log` as l LEFT JOIN `cases` as c ON l.case_id=c.id 
                 WHERE l.status=0 AND c.mediator_id=:adm_id ";
        $data[':adm_id'] = $adm_id;
        //上一页
        if ($type == 1) {
            $sql .= ' AND l.id > :id';  //倒叙排列
            $data[':id'] = $id;
            $sql .= ' ORDER BY l.id ASC';
        }

        //下一页
        if ($type == 2) {
            $sql .= ' AND l.id < :id';  //倒叙排列
            $data[':id'] = $id;
            $sql .= ' ORDER BY l.id DESC';
        }

        $sql .= ' limit 1';
        return $this->dao->conn()->setTag(self::$tag)->preparedSql($sql, $data)->fetchOne();
    }

    /**
     * @desc 分页查询 获取上一页 下一页 id
     *
     * @param int $type 1上一页  2 下一页
     *
     * @return mixed
     */
    public function getPageIdNew($type, $id, $adm,$auditrepay)
    {
        $data = [];
        if($auditrepay){
            $sql = "SELECT l.*,c.mediator_id FROM `case_repay_log` as l LEFT JOIN `cases` as c ON l.case_id=c.id 
                 WHERE l.status=0 AND c.upload_firm_type=:user_type ";

            $data[':user_type'] = $adm['user_type'];
            if($adm['user_type'] != 1 ){
                $sql .= " AND c.upload_firm_id=:firm_id ";
                $data[':firm_id'] = $adm['firm_id'];

            }
            //上一页
            if ($type == 1) {
                $sql .= ' AND l.id > :id';  //倒叙排列
                $data[':id'] = $id;
                $sql .= ' ORDER BY l.id ASC';
            }

            //下一页
            if ($type == 2) {
                $sql .= ' AND l.id < :id';  //倒叙排列
                $data[':id'] = $id;
                $sql .= ' ORDER BY l.id DESC';
            }

            $sql .= ' limit 1';
            return $this->dao->conn()->setTag(self::$tag)->preparedSql($sql, $data)->fetchOne();
        }else{
            $sql = "SELECT * FROM `case_repay_log` WHERE status=0 AND upload_uid =:adm_id ";
            $data[':adm_id'] = $adm['id'];
            //上一页
            if ($type == 1) {
                $sql .= ' AND id > :id';  //倒叙排列
                $data[':id'] = $id;
                $sql .= ' ORDER BY id ASC';
            }

            //下一页
            if ($type == 2) {
                $sql .= ' AND id < :id';  //倒叙排列
                $data[':id'] = $id;
                $sql .= ' ORDER BY id DESC';
            }

            $sql .= ' limit 1';
            return $this->dao->conn()->setTag(self::$tag)->preparedSql($sql, $data)->fetchOne();
        }

    }


    /**
     * @desc 原告上传资料
     * @param array $data
     * @param $uid
     * @param $name
     * @return array
     */
    public function saveData(array $data, $uid, $name)
    {
        try {
            $this->dao->conn(false)->beginTransaction();
            $return = ['code' => 0, 'msg' => ''];
            $repay_status = 0;
            // 查询案件信息
            $caseData = Module_Mediate_Case::getInstance()->getInfoPidHTBH($data['plaintiff_id'],$data['contract_code']);
            if (empty($caseData)) {
                $this->dao->rollback();
                $return['code'] = 1;
                $return['msg'] = '录入失败:合同编号与原告方信息不匹配!'.$data['plaintiff_id'].$data['contract_code'];
                return $return;
            }
            $data['plaintiff_name'] = $caseData['plaintiff_name'];
            $data['update_time'] = time();
            $data['add_time'] = time();
            $data['status'] = $repay_status;
            $data['case_id'] = $caseData['id'];
            $data['upload_uid'] = $uid;
            try {
                if (!$insertId = Module_Mediate_CaseRepayLog::getInstance()->singleInsert($data)) {
                    $this->dao->rollback();
                    Func_Log::write('ParseXlsx', 'debug', '还款信息录入失败，data=' . var_export($data, 1));
                    $return['code'] = 1;
                    $return['msg'] = '录入失败:还款信息录入异常!';
                    return $return;
                }
            } catch (PDOException $e) {
                $e->getMessage();
                Func_Log::write('ParseXlsx', 'debug,pdo异常=', json_encode($e->getMessage()).'data=' . var_export($data, 1));
                $this->dao->rollback();
                $return['code'] = 1;
                $return['msg'] = '录入失败:还款信息录入异常!';
                return $return;
            }
            //操作日志
            $insertdata = array(
                'case_id' => $caseData['id'],
                'status' => "entry_repay",
                'operation_uid' => $uid,
                'operation_name' => $name,
                'operation_content' => '上传提交还款记录',
                'create_ts' => time(),
            );

            $OperationLog = Module_Mediate_CaseOperationLog::getInstance()->insert($insertdata);
            if (empty($OperationLog)) {
                $this->dao->rollback();
                Func_Log::write('ParseXlsx', '$OperationLog操作日志写入失败', json_encode($insertdata));
                $return['code'] = 1;
                $return['msg'] = '录入失败:操作日志写入异常!';
                return $return;
            }

            $this->dao->commit();
            $this->dao->clearTag(self::$tag);
            $this->dao->clearTag('Model_Mediate_Case');
            return $return;
        } catch (Exception $e) {
            Func_Log::write('ParseXlsx', '异常', json_encode($updata));
            $this->dao->rollback();
            $return['code'] = 1;
            $return['msg'] = '录入失败:异常!';
            return $return;
        }
    }

    /**
     * @desc 原告上传资料 定时任务
     * @param $case_id
     * @param $id
     * @return bool
     */
    public function timingSaveData($case_id, $id)
    {
        try {
            $this->dao->conn(false)->beginTransaction();
            $caseInfo = Module_Mediate_Case::getInstance()->getItemById($case_id);
            if ($caseInfo['case_status'] >= 3 && $caseInfo['case_status'] != 13) {
                $is_more = 0;
                $status0 = $this->getOneByCaseId($case_id);
                if (!empty($status0) && count($status0) > 0) {
                    $is_more = 1;
                }
                $status = 18;
                $remark = $caseInfo['adm_id'] . '|' . $caseInfo['adm_name'];
                if ($is_more) {
                    $status = 19;
                    $remark = '';
                }
                //操作日志
                $insertdata = array(
                    'case_id' => $case_id,
                    'status' => $status,
                    'operation_uid' => 0,
                    'operation_name' => '系统执行',
                    'operation_content' => '系统执行原告提交还款记录',
                    'remark' => $remark,
                    'create_ts' => time(),
                );

                $OperationLog = Module_Mediate_CaseOperationLog::getInstance()->insert($insertdata);
                if (empty($OperationLog)) {
                    $this->dao->rollback();
                    Func_Log::write('timingparsexlsx', '$OperationLog操作日志写入失败', json_encode($insertdata));
                    return false;
                }

                $saveData = [
                    'id' => $id,
                    'status' => 0,
                ];
                $log_res = Module_Mediate_CaseRepayLog::getInstance()->singleUpdate($saveData);
                if (!$log_res) {
                    Func_Log::write("timingparsexlsx", '更新失败', var_export($saveData, true));
                    $this->dao->rollback();
                    return false;
                }
                $nextuser = Lib_NextUser::getInstance()->getNextUser($case_id, 0, 0, 2);
                //修改经办人
                $updata = [];
                $updata['adm_name'] = $nextuser['adm_name'];//指定下一步经办人
                $updata['adm_id'] = $nextuser['adm_id'];//指定下一步经办人
                $updata['is_repayment'] = 2;
                $updata['update_time'] = time();

                $res_adm_id = Module_Mediate_Case::getInstance()->update($updata, $case_id);
                if (empty($res_adm_id) && $res_adm_id !== 0) {
                    $this->dao->rollback();
                    Func_Log::write('timingparsexlsx', '修改经办人失败', json_encode($updata));
                    return false;
                }
                if($caseInfo['notice_status'] < 3){
                    //调用法院接口  STOP 暂停 ACTION 继续流程  END 结束
                    $tcp_data = array('task_type' => 'case_operationCase', 'task_data' => ['id' => $case_id, 'operation' => 'STOP']);
                    Func_Log::write("realtimeSend", '$tcp_data_STOP', json_encode($tcp_data));
                    $tcp_res = Lib_Request_TcpClient::getInstance()->singleSend($tcp_data);
                    if (empty($tcp_res)) {
                        Func_Log::write("realtimeSend", 'rollback_error', var_export($tcp_res, true));
                        $this->dao->rollback();
                        return false;
                    }
                }

                $this->dao->commit();
                $this->dao->clearTag(self::$tag);
                $this->dao->clearTag('Model_Mediate_Case');
            }
        } catch (Exception $e) {
            Func_Log::write('timingparsexlsx', '异常$id=' . $id);
            $this->dao->rollback();
            return false;
        }
    }

    /**
     * @desc 确认还款
     * @param $id
     * @param $status
     * @return bool
     */
    public function updateStatus($id, $status, $userinfo)
    {
        try {
            $return = array('code' => 1, 'msg' => '');
            $this->dao->conn(false)->beginTransaction();
            $info = Module_Mediate_CaseRepayLog::getInstance()->getOne(['*'], ["id={$id}"]);
            $res_case = Module_Mediate_Case::getInstance()->getInfoById($info['case_id']);
            $res_caseAddition = Module_Mediate_CaseAddition::getInstance()->getInfoById($info['case_id'], true);
            $is_last = Module_Mediate_CaseRepayLog::getInstance()->isLast($info['case_id'], $id);
            $info_status1 = Module_Mediate_CaseRepayLog::getInstance()->getOne(['*'], ["case_id={$info['case_id']}", "status=1"]);

            //初始化日志
            $log = array(
                'case_id' => $info['case_id'],
                'status' => $status,
                'CaseRepayLog_id' => $id,
                'old_log' => array(
                    'reduce_debt_principal' => $res_caseAddition['reduce_debt_principal'], //扣减后欠款本金
                    'interest' => $res_caseAddition['interest'], //利息
                    'overdue_interest' => $res_caseAddition['overdue_interest'], //逾期利息
                    'service_fee' => $res_caseAddition['service_fee'],  //服务费
                    'liquidated_damages' => $res_caseAddition['liquidated_damages'],//违约金
                    'total_arrears' => $res_caseAddition['total_arrears'], //欠款总额
                   // 'target_amount' => $res_caseAddition['target_amount']  //
                ),
                'changge' => array(
                    'repay_amount' => $info['repay_amount'],
                    'repay_interest' => $info['repay_interest'],
                    'replay_ai' => $info['replay_ai'],
                ),
                'repayment_date' => !empty($info_status1['repayment_date']) ? date("Y-m-d", $info_status1['repayment_date']) : '--'
            );

          /*  //偿还本金
            $debt_principal = Func_Calculation_Calculation::buildMoney($res_caseAddition['debt_principal']);
            $debt_principal_arr = array('debt_principal' => $debt_principal);
            $debt_principal_arr = Func_Common::getInstance()->chargeback($debt_principal_arr, $info['repay_amount']);*/
            //扣减后欠款本金
            $reduce_debt_principal_arr = $interest_arr = $chage_arr = [];
            if($info['repay_amount']){
                $reduce_debt_principal = Func_Calculation_Calculation::buildMoney($res_caseAddition['reduce_debt_principal']);
                $reduce_debt_principal_arr = array('reduce_debt_principal' => $reduce_debt_principal);
                $reduce_debt_principal_arr = Func_Common::getInstance()->chargeback($reduce_debt_principal_arr, $info['repay_amount']);

            }

            //偿还利息
            if($info['repay_interest']){
                $interest = Func_Calculation_Calculation::buildMoney($res_caseAddition['interest']);
                $interest_arr = array('interest' => $interest);
                $interest_arr = Func_Common::getInstance()->chargeback($interest_arr, $info['repay_interest']);
            }


            //其他费用  扣减顺序  服务费 违约金 逾期利息
            if($info['replay_ai']){
                $overdue_interest = Func_Calculation_Calculation::buildMoney($res_caseAddition['overdue_interest']);
                $service_fee = Func_Calculation_Calculation::buildMoney($res_caseAddition['service_fee']);
                $liquidated_damages = Func_Calculation_Calculation::buildMoney($res_caseAddition['liquidated_damages']);
                $chage_arr = array(
                    'service_fee' => $service_fee,
                    'liquidated_damages' => $liquidated_damages,
                    'overdue_interest' => $overdue_interest,
                );
                $chage_arr = Func_Common::getInstance()->chargeback($chage_arr, $info['replay_ai']);
            }


            $updata = array_merge($reduce_debt_principal_arr, $interest_arr, $chage_arr);
            //欠款总额   获取案件模板信息
            $temInfo = Module_Mediate_PlaintiffTemplate::getInstance()->getOne(['conf_file'], ["id={$res_case['template_id']}", "plaintiff_id={$res_case['plaintiff_id']}"]);
            $confInfo = json_decode($temInfo['conf_file'], 1);
            if (empty($confInfo)) {
                $return['msg'] = '未能获取到案件模板';
                $this->dao->rollback();
                return $return;
            }
            $formulaArr = [];
            foreach ($confInfo as $k => $v) {
               // if (!empty($v['formula']) && ($k == 'total_arrears' || $k == 'target_amount')) {
                if (!empty($v['formula']) && ($k == 'total_arrears')) {
                    $formulaArr[$k] = $v['formula'];
                }
            }
            $res_caseAddition['reduce_debt_principal'] = $updata['reduce_debt_principal'];
            $res_caseAddition['interest'] = $updata['interest'];
            $res_caseAddition['overdue_interest'] = $updata['overdue_interest'];
            $res_caseAddition['service_fee'] = $updata['service_fee'];
            $res_caseAddition['liquidated_damages'] = $updata['liquidated_damages'];
            //欠款总额 公式计算
            $total_arrears = Func_Case::formula($formulaArr, $res_caseAddition);
            if (isset($total_arrears['total_arrears'])) {
                $updata['total_arrears'] = $total_arrears['total_arrears'];
            }
            //标的金额 公式计算
           /* if (isset($total_arrears['target_amount'])) {
                $updata['target_amount'] = $total_arrears['target_amount'];
            }*/
            $log['updata'] = $updata;

            Func_Log::write("ModelCaseRepayLog", '$log', var_export($log, true));
            $res1 = Module_Mediate_CaseAddition::getInstance()->update($updata, $info['case_id']);
            if (!$res1 && $res1 !== 0) {
                Func_Log::write('ModelCaseRepayLog', '$log_error', json_encode($log));
                $this->dao->rollback();
                $return['msg'] = '数据更新失败';
                $this->dao->rollback();
                return $return;

            }

            //处理额外计算的逾期利息
            if (!empty($info['repay_amount']) && $temInfo['is_everyday_count'] == 1) {
                $repayment_date = '';
                $repay_amount = $info['repay_amount'];
                // 结案特殊处理

                if ($status == 1) {
                    $repay_amount = $log['old_log']['debt_principal']; //这里需要用本金 进行计算
                    $log['updata']['repay_amount_debt_principal'] = $repay_amount;
                } else if (!empty($info_status1) && $info_status1['repayment_date']) {
                    //案件已经结束,进行扣款
                    $repayment_date = date("Y-m-d", $info_status1['repayment_date']);
                }

                if ($repay_amount) {
                    $res4 = Func_Case::calculateOverdueDiffValue($info['case_id'], $repay_amount, date("Y-m-d", $info['repayment_date']), date("Y-m-d", time()), $repayment_date);
                    if (!$res4 || $res4['code'] != 0) {
                        Func_Log::write('ModelCaseRepayLog', '$res4', json_encode($res4));
                        $return['msg'] = $res4['msg'];
                        $this->dao->rollback();
                        return $return;
                    }
                }
            }
            $updata2 = array('status' => $status, 'update_time' => time(), 'id' => $id);
            $res2 = Module_Mediate_CaseRepayLog::getInstance()->singleUpdate($updata2);
            if (!$res2) {
                Func_Log::write('ModelCaseRepayLog', '$updata2', json_encode($updata2));
                $return['msg'] = '数据更新失败';
                $this->dao->rollback();
                return $return;
            }

            //扣除还款并结案 修改案件状态 ->结案
            if ($status == 1) {
                $updata3 = array('case_status' => 20, 'update_time' => time());
                $res3 = Module_Mediate_Case::getInstance()->update($updata3, $info['case_id']);
                if (!$res3) {
                    Func_Log::write('ModelCaseRepayLog', '$updata3', json_encode($updata3));
                    $return['msg'] = '数据更新失败';
                    $this->dao->rollback();
                    return $return;
                }
                if($res_case['notice_status'] < 3){
                    //调用法院接口  STOP 暂停 ACTION 继续流程  END 结束
                    $tcp_data = array('task_type' => 'case_operationCase', 'task_data' => ['id' => $res_case['id'], 'operation' => 'END']);
                    Func_Log::write("realtimeSend", '$tcp_data_END', json_encode($tcp_data));
                    $tcp_res = Lib_Request_TcpClient::getInstance()->singleSend($tcp_data);
                    if (empty($tcp_res)) {
                        $this->dao->rollback();
                        $return['msg'] = '网络异常,请稍后重试';
                        Func_Log::write("realtimeSend", 'rollback_error', var_export($tcp_res, true));
                        return $return;
                    }
                }


                //调解成功
                $tasks= [
                    'task_type' => 'case_submitCaseStatus',
                    'task_data' => ['id' => $res_case['id'], 'uid' => $userinfo['id'], 'name' => $userinfo['name']],
                ];

                $tcp_res = Lib_Request_TcpClient::getInstance()->singleSend($tasks);
                if (!$tcp_res) {
                    $this->dao->rollback();
                    Func_Log::write("realtimeSend", 'rollback_case_submitCaseStatus', var_export($tcp_res, true));
                    return $return;
                }

            } else {
                //还款情况审核列表 只剩最后一条记录,修改 is_repayment状态  修改经办人
                if ($is_last) {
                    $nextuser = Lib_NextUser::getInstance()->getNextUser($info['case_id'], 0, 0, 1);
                    $updata3 = array(
                        'is_repayment' => 1,
                        'update_time' => time(),
                        'adm_name' => $nextuser['adm_name'],  //指定下一步经办人
                        'adm_id' => $nextuser['adm_id'], //指定下一步经办人
                    );

                    $res3 = Module_Mediate_Case::getInstance()->update($updata3, $info['case_id']);
                    if (!$res3 && $res3 !== 0) {
                        Func_Log::write('ModelCaseRepayLog', '$updata3', json_encode($updata3));
                        $return['msg'] = '数据更新失败';
                        $this->dao->rollback();
                        return $return;
                    }
                    //调用法院接口  STOP 暂停 ACTION 继续流程  END 结束
                    if ($res_case['case_status'] != 20 && $res_case['notice_status'] < 3) { //如果案件已经结束,紧扣款时候,不调法院接口,
                        $tcp_data = array('task_type' => 'case_operationCase', 'task_data' => ['id' => $res_case['id'], 'operation' => 'ACTION']);
                        Func_Log::write("realtimeSend", '$tcp_data_ACTION', json_encode($tcp_data));
                        $tcp_res = Lib_Request_TcpClient::getInstance()->singleSend($tcp_data);
                        if (empty($tcp_res)) {
                            $this->dao->rollback();
                            $return['msg'] = '网络异常,请稍后重试';
                            Func_Log::write("realtimeSend", 'rollback_error', var_export($tcp_res, true));
                            return $return;
                        }
                    }
                }
            }
            $this->dao->commit();
            $this->dao->clearTag(self::$tag);
            $return['code'] = 0;
            return $return;
        } catch (Exception $e) {
            $this->dao->rollback();
            Func_Log::write("ModelCaseRepayLog", '$e', var_export($e->getMessage(), true));
            return false;
        }
    }

    /**
     * @desc 信息有误关闭
     * @param $id
     * @param $status
     * @return bool
     */
    public function closeRepayLog($id, $status)
    {
        try {
            $this->dao->conn(false)->beginTransaction();
            $info = Module_Mediate_CaseRepayLog::getInstance()->getOne(['*'], ["id={$id}"]);
            $res_case = Module_Mediate_Case::getInstance()->getInfoById($info['case_id']);
            if ($info) {
                $is_last = Module_Mediate_CaseRepayLog::getInstance()->isLast($info['case_id'], $id);
                $singleupdate = ["status" => $status, "id" => $id];
                $res = Module_Mediate_CaseRepayLog::getInstance()->singleUpdate($singleupdate);
                if ($res || $res === 0) {
                    //还款情况审核列表 只剩最后一条记录,修改 is_repayment状态 修改经办人
                    if ($is_last) {
                        $nextuser = Lib_NextUser::getInstance()->getNextUser($info['case_id'], 0, 0, 1);
                        if (empty($nextuser)) {
                            $this->dao->rollback();
                            return false;
                        }
                        $updata3 = array(
                            'is_repayment' => 1,
                            'update_time' => time(),
                            'adm_name' => $nextuser['adm_name'],  //指定下一步经办人
                            'adm_id' => $nextuser['adm_id'], //指定下一步经办人
                        );
                        $res3 = Module_Mediate_Case::getInstance()->update($updata3, $info['case_id']);
                        if (!$res3 && $res3 !== 0) {
                            $this->dao->rollback();
                            return false;
                        }
                        //调用法院接口  STOP 暂停 ACTION 继续流程  END 结束
                        if ($res_case['case_status'] != 20 && $res_case['notice_status'] < 3) { //如果案件已经结束,信息有误关闭,不调法院接口,
                            $tcp_data = array('task_type' => 'case_operationCase', 'task_data' => ['id' => $res_case['id'], 'operation' => 'ACTION']);
                            Func_Log::write("realtimeSend", '$tcp_data_ACTION', json_encode($tcp_data));
                            $tcp_res = Lib_Request_TcpClient::getInstance()->singleSend($tcp_data);
                            if (empty($tcp_res)) {
                                $return['msg'] = '网络异常，请稍后重试';
                                $this->dao->rollback();
                                Func_Log::write("realtimeSend", 'rollback_error', var_export($tcp_res, true));
                                return $return;
                            }
                        }
                    }
                } else {
                    $this->dao->rollback();
                    return false;
                }
            }

            $this->dao->commit();
            $this->dao->clearTag(self::$tag);
            $this->dao->clearTag('Model_Mediate_Case');
            return true;
        } catch (Exception $e) {
            $this->dao->rollback();
            return false;
        }
    }


    /**
     * 获取全部数据.
     *
     * @return array
     */
    public function getAllList($search, $count = false, $cache = false)
    {
        $fields = $count ? ' count(*) as num ' : ' * ';
        $search_str = '';
        if (isset($search['where']) && !empty($search['where'])) {
            foreach ($search['where'] as $key => $value) {
                $temp = ':' . $key;
                $arr[] = ' `' . $key . '`=' . $temp;
                $data[$temp] = $value;
            }
            $search_str .= 'WHERE ' . implode(' AND ', $arr);
        }
        if (!$count) {
            if (isset($search['order']) && $search['order']) {
                $search_str .= ' ORDER BY ' . $search['order'];
            } else {
                $search_str .= ' ORDER BY `id` DESC';
            }
            if (isset($search['limit']) && $search['limit']) {
                $search['start'] = isset($search['start']) ? $search['start'] : 0;
                $data[':start'] = $search['start'];
                $data[':limit'] = $search['limit'];
                $search_str .= ' LIMIT :start,:limit';
            }
        }

        $sql = "SELECT {$fields} FROM {$this->table} {$search_str}";

        $cache ? $this->dao->conn()->setTag(self::$tag) : $this->dao->conn(false)->noCache();
        $res = $this->dao->preparedSql($sql, $data)->fetchAll();
        if ($count) {
            return $res[0]['num'];
        }

        return $res;
    }

    /**
     * 获取全部数据(经办人)
     *
     * @return array
     */
    public function getAllByAmdId($adm_id,$where, $count = false, $start, $limit, $cache = false)
    {
        $data = [];
        $fields = $count ? ' count(*) as num ' : ' l.*,c.mediator_id,c.mediator_name,c.case_status,c.litigantName';

        $sql = "SELECT {$fields} FROM `case_repay_log` as l LEFT JOIN `cases` as c ON l.case_id=c.id ";

        $sql .= " WHERE ((c.mediator_id = :adm_id AND c.firm_mediator_id = 0) OR c.firm_mediator_id = :adm_id) ";

        if($where){
            $sql .=  "AND " . implode(' AND ', $where);
        }

        $data[':adm_id'] = $adm_id;
        if (!$count) {
            $sql .= " ORDER BY l.id DESC ";
        }
        if ($limit && $count == false) {
            $sql .= " LIMIT :start,:limit";
            $data[':start'] = $start;
            $data[':limit'] = $limit;
        }
        $cache ? $this->dao->conn()->setTag(self::$tag) : $this->dao->conn(false)->noCache();
        $res = $this->dao->preparedSql($sql, $data)->fetchAll();
        if ($count) {
            return $res[0]['num'];
        }

        return $res;
    }



    public function  getlistByAmd($user_type, $firm_id ,$type, $start, $limit , $count ,$cache)
    {
        $data = [];
        $fields = $count ? ' count(*) as num ' : ' l.*,c.upload_firm_id,c.upload_firm_type,c.case_status,c.litigantName';

        $sql = "SELECT {$fields} FROM `case_repay_log` as l LEFT JOIN `cases` as c ON l.case_id=c.id ";

        if($type == 1){
            $sql .= 'WHERE l.status = 0 ';
        }else{
             $sql .= 'WHERE status in (1,2,3) ';

        }
        $sql .= "AND c.upload_firm_type = :user_type ";
        $data[':user_type'] = $user_type;

        if($user_type != 1){
            $sql .= "AND c.upload_firm_id = :firm_id ";
            $data[':firm_id'] = $firm_id;
        }
        if (!$count) {
            $sql .= " ORDER BY l.id DESC ";
        }
        if ($limit && $count == false) {
            $sql .= " LIMIT :start,:limit";
            $data[':start'] = $start;
            $data[':limit'] = $limit;
        }
        $cache ? $this->dao->conn()->setTag(self::$tag) : $this->dao->conn(false)->noCache();
        $res = $this->dao->preparedSql($sql, $data)->fetchAll();
        if ($count) {
            return $res[0]['num'];
        }

        return $res;
    }
    public function getOneByCaseId($case_id = 0)
    {
        $sql = 'SELECT * FROM `case_repay_log` WHERE `case_id`=:case_id AND `status`=0';
        $data = array(':case_id' => $case_id);
        return $this->dao->conn(false)->noCache()->preparedSql($sql, $data)->fetchAll();
    }

    /**
     * 根据被告人上传信息更新数据表
     *  如果case_repay_log没有任何数据
     *       case_repay_log  新增
     *       case_operation_log   新增  18  remark 需要更新case中的数据
     *       cases   更新 获取到的经办人
     *  如果case_repay_log有数据
     *      有0的状态
     *         case_repay_log  更新
     *         case_operation_log   新增 19
     *      没有0的状态
     *         case_repay_log  新增
     *         case_operation_log   新增  18  remark 需要更新case中的数据
     *         cases   更新 获取到的经办人
     *
     * @param array $caseData
     * @return array
     */
    public function updateByDefendantUploadData(string $filePath, array $caseData): bool
    {
        // begin Transaction
        $this->dao->conn(false);
        $this->dao->noCache();
        $this->dao->beginTransaction();

        // 查询数据库是否有该条记录
        $search = [];
        $search['where'] = ["case_id={$caseData['id']}"];
        $ret = Module_Mediate_CaseRepayLog::getInstance()->getAllBySearch(['id', 'status'], $search);
        /*
        *  如果case_repay_log没有任何数据 
        *       case_repay_log  新增
        *       case_operation_log   新增  18  remark 需要更新case中的数据
        *       cases   更新 获取到的经办人
        */
        $replyLogData = [
            'plaintiff_name' => $caseData['plaintiff_name'],
            'plaintiff_id' => $caseData['plaintiff_id'],
            'contract_code' => $caseData['contract_code'],
            'agent_id' => $caseData['agent_id'],
            'agent_name' => $caseData['agent_name'],
            'defendant_name' => $caseData['defendant_name'],
            'update_time' => time(),
            'filepath' => $filePath,
            'case_id' => $caseData['id'],
            'defendant_update_time' => time(),
        ];
        $opLogData = [
            'case_id' => $caseData['id'],
            'status' => 18,
            'operation_uid' => 0,
            'operation_name' => '当事人',
            'operation_content' => '提交还款凭证',
            'remark' => $caseData['adm_id'] . '|' . $caseData['adm_name'],
            'create_ts' => time(),
        ];
        if (!$ret) {
            // case_repay_log  新增
            $replyLogLastInsertId = Module_Mediate_CaseRepayLog::getInstance()->singleInsert($replyLogData);
            if (!$replyLogLastInsertId) {
                $this->dao->rollback();
                return 0;
            }
            $this->dao->clearTag('Module_Mediate_CaseRepayLog');

            // case_operation_log   新增  18  remark 需要更新case中的数据
            $opLogLastInsertId = Module_Mediate_CaseOperationLog::getInstance()->singleInsert($opLogData);
            if (!$opLogLastInsertId) {
                $this->dao->rollback();
                return 0;
            }
            $this->dao->clearTag('Module_Mediate_CaseOperationLog');

            // cases update
            //  获取经办人 
            $adm = Lib_NextUser::getInstance()->getNextUser($caseData['id'], 0, 0, 2, 0);

            $caseData = [
                'id' => $caseData['id'],
                'adm_id' => $adm['adm_id'],
                'adm_name' => $adm['adm_name'],
                'update_time' => time(),
                'is_repayment' => 2,
            ];
            $caseAffectRow = Module_Mediate_Case::getInstance()->singleUpdate($caseData);
            if (!$caseAffectRow) {
                $this->dao->rollback();
                return 0;
            }
            $this->dao->clearTag('Module_Mediate_Case');
            $this->dao->commit();
            return true;
        }

        /**
         *  如果case_repay_log有数据
         *      有0的状态
         *         case_repay_log  更新
         *         case_operation_log   新增 19
         *      没有0的状态
         *         case_repay_log  更新并且新增
         *         case_operation_log   新增  18  remark 需要更新case中的数据
         *         cases   更新 获取到的经办人
         */

        // 更新 case_repay_log 中原来的数据
        $replyLogData = [
            'plaintiff_name' => $caseData['plaintiff_name'],
            'plaintiff_id' => $caseData['plaintiff_id'],
            'contract_code' => $caseData['contract_code'],
            'agent_id' => $caseData['agent_id'],
            'agent_name' => $caseData['agent_name'],
            'defendant_name' => $caseData['defendant_name'],
            'update_time' => time(),
            'filepath' => $filePath,
            'case_id' => $caseData['id'],
            'defendant_update_time' => time(),
        ];
        $replyLogAffectRow = Module_Mediate_CaseRepayLog::getInstance()->singleUpdate($replyLogData, 'case_id');
        if (!$replyLogAffectRow) {
            $this->dao->rollback();
            return 0;
        }
        $this->dao->clearTag('Module_Mediate_CaseRepayLog');
        $opLogData['status'] = 19;
        $opLogData['remark'] = '';

        if (!in_array(0, array_column($ret, 'status'))) {
            $replyLogLastInsertId = Module_Mediate_CaseRepayLog::getInstance()->singleInsert($replyLogData);
            if (!$replyLogLastInsertId) {
                $this->dao->rollback();
                return 0;
            }
            $this->dao->clearTag('Module_Mediate_CaseRepayLog');

            $opLogData['status'] = 18;
            $opLogData['remark'] = $caseData['adm_id'] . '|' . $caseData['adm_name'];

            // cases update
            //  获取经办人 
            $adm = Lib_NextUser::getInstance()->getNextUser($caseData['id'], 0, 0, 2, 0);
            $caseData = [
                'id' => $caseData['id'],
                'adm_id' => $adm['adm_id'],
                'adm_name' => $adm['adm_name'],
                'update_time' => time(),
                'is_repayment' => 2,
            ];
            $caseAffectRow = Module_Mediate_Case::getInstance()->singleUpdate($caseData);
            if (!$caseAffectRow) {
                $this->dao->rollback();
                return 0;
            }
            $this->dao->clearTag('Module_Mediate_Case');
        }
        // case_operation_log  新增
        $opLogLastInsertId = Module_Mediate_CaseOperationLog::getInstance()->singleInsert($opLogData);
        if (!$opLogLastInsertId) {
            $this->dao->rollback();
            return 0;
        }
        $this->dao->clearTag('Module_Mediate_CaseOperationLog');
        $this->dao->commit();
        return true;
    }

    //获取案件还款总额
    public function getCaseRepayAmount($case_id){
        $sql = "SELECT sum(repay_amount)+sum(repay_interest) +sum(replay_ai) as total_amount FROM `case_repay_log` where case_id = :case_id  AND status in (1,2) ";
        $data[':case_id'] = $case_id;

        return $this->dao->conn()->setTag(self::$tag)->preparedSql($sql, $data)->fetchOne();
    }
}
